import React, { useState, useEffect } from 'react';
import { Modal, Row, Col, Statistic, Progress, Card, Typography, Spin, Tag, Divider } from 'antd';
import { 
  TrophyOutlined, 
  ClockCircleOutlined, 
  CheckCircleOutlined,
  FireOutlined,
  AimOutlined,
  BookOutlined
} from '@ant-design/icons';
import { statisticsService } from '../services/api';

const { Title, Text } = Typography;

interface TodayStatsModalProps {
  visible: boolean;
  onCancel: () => void;
}

interface TodayStats {
  today: {
    focus_sessions: number;
    focus_duration: number;
    tasks_completed: number;
    points_earned: number;
    work_sessions: number;
    break_sessions: number;
  };
  total_points: number;
  streak_days: number;
  week: {
    week_focus_sessions: number;
    week_focus_duration: number;
    week_tasks_completed: number;
    week_points_earned: number;
  };
  month: {
    month_focus_sessions: number;
    month_focus_duration: number;
    month_tasks_completed: number;
    month_points_earned: number;
  };
}

const TodayStatsModal: React.FC<TodayStatsModalProps> = ({ visible, onCancel }) => {
  const [loading, setLoading] = useState(false);
  const [stats, setStats] = useState<TodayStats | null>(null);

  const loadStats = async () => {
    setLoading(true);
    try {
      const response = await statisticsService.getTodayStats();
      if ((response as any).success) {
        setStats((response as any).data);
      }
    } catch (error) {
      console.error('加载统计数据失败:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (visible) {
      loadStats();
    }
  }, [visible]);

  const formatDuration = (seconds: number) => {
    // 后端返回的是秒数，需要转换为分钟
    const minutes = Math.floor(seconds / 60);
    const hours = Math.floor(minutes / 60);
    const mins = minutes % 60;
    if (hours > 0) {
      return `${hours}小时${mins}分钟`;
    }
    return `${mins}分钟`;
  };

  const getStreakColor = (days: number) => {
    if (days >= 30) return '#f50';
    if (days >= 7) return '#fa8c16';
    if (days >= 3) return '#52c41a';
    return '#1890ff';
  };

  const getStreakText = (days: number) => {
    if (days >= 30) return '传奇';
    if (days >= 7) return '大师';
    if (days >= 3) return '达人';
    return '新手';
  };

  return (
    <Modal
      title={
        <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
          <TrophyOutlined style={{ color: '#faad14' }} />
          <span>今日统计</span>
        </div>
      }
      open={visible}
      onCancel={onCancel}
      footer={null}
      width={800}
      style={{ top: 20 }}
    >
      {loading ? (
        <div style={{ textAlign: 'center', padding: '40px 0' }}>
          <Spin size="large" />
        </div>
      ) : stats ? (
        <div>
          {/* 今日概览 */}
          <Card style={{ marginBottom: 16 }}>
            <Title level={4} style={{ marginBottom: 16 }}>今日概览</Title>
            <Row gutter={[16, 16]}>
              <Col xs={12} sm={6}>
                <Statistic
                  title="专注会话"
                  value={stats.today.focus_sessions}
                  suffix="次"
                  prefix={<AimOutlined />}
                  valueStyle={{ color: '#1890ff' }}
                />
              </Col>
              <Col xs={12} sm={6}>
                <Statistic
                  title="专注时长"
                  value={formatDuration(stats.today.focus_duration)}
                  prefix={<ClockCircleOutlined />}
                  valueStyle={{ color: '#52c41a' }}
                />
              </Col>
              <Col xs={12} sm={6}>
                <Statistic
                  title="完成任务"
                  value={stats.today.tasks_completed}
                  suffix="个"
                  prefix={<CheckCircleOutlined />}
                  valueStyle={{ color: '#722ed1' }}
                />
              </Col>
              <Col xs={12} sm={6}>
                <Statistic
                  title="获得积分"
                  value={stats.today.points_earned}
                  prefix={<TrophyOutlined />}
                  valueStyle={{ color: '#faad14' }}
                />
              </Col>
            </Row>
          </Card>

          {/* 连续学习 */}
          <Card style={{ marginBottom: 16 }}>
            <Row gutter={[16, 16]} align="middle">
              <Col xs={24} sm={12}>
                <div style={{ textAlign: 'center' }}>
                  <div style={{ fontSize: '48px', color: getStreakColor(stats.streak_days), marginBottom: '8px' }}>
                    <FireOutlined />
                  </div>
                  <Title level={3} style={{ margin: 0, color: getStreakColor(stats.streak_days) }}>
                    {stats.streak_days}天
                  </Title>
                  <Text type="secondary">连续学习</Text>
                  <div style={{ marginTop: '8px' }}>
                    <Tag color={getStreakColor(stats.streak_days)}>
                      {getStreakText(stats.streak_days)}
                    </Tag>
                  </div>
                </div>
              </Col>
              <Col xs={24} sm={12}>
                <div>
                  <Title level={5}>本周表现</Title>
                  <div style={{ marginBottom: '8px' }}>
                    <Text>专注会话: {stats.week.week_focus_sessions}次</Text>
                  </div>
                  <div style={{ marginBottom: '8px' }}>
                    <Text>专注时长: {formatDuration(stats.week.week_focus_duration)}</Text>
                  </div>
                  <div style={{ marginBottom: '8px' }}>
                    <Text>完成任务: {stats.week.week_tasks_completed}个</Text>
                  </div>
                  <div>
                    <Text>获得积分: {stats.week.week_points_earned}分</Text>
                  </div>
                </div>
              </Col>
            </Row>
          </Card>

          {/* 本月统计 */}
          <Card>
            <Title level={4} style={{ marginBottom: 16 }}>本月统计</Title>
            <Row gutter={[16, 16]}>
              <Col xs={12} sm={6}>
                <Statistic
                  title="专注会话"
                  value={stats.month.month_focus_sessions}
                  suffix="次"
                  valueStyle={{ color: '#1890ff' }}
                />
              </Col>
              <Col xs={12} sm={6}>
                <Statistic
                  title="专注时长"
                  value={formatDuration(stats.month.month_focus_duration)}
                  valueStyle={{ color: '#52c41a' }}
                />
              </Col>
              <Col xs={12} sm={6}>
                <Statistic
                  title="完成任务"
                  value={stats.month.month_tasks_completed}
                  suffix="个"
                  valueStyle={{ color: '#722ed1' }}
                />
              </Col>
              <Col xs={12} sm={6}>
                <Statistic
                  title="获得积分"
                  value={stats.month.month_points_earned}
                  valueStyle={{ color: '#faad14' }}
                />
              </Col>
            </Row>
          </Card>

          {/* 总积分 */}
          <div style={{ textAlign: 'center', marginTop: '16px', padding: '16px', background: '#f5f5f5', borderRadius: '8px' }}>
            <div style={{ fontSize: '24px', color: '#faad14', marginBottom: '8px' }}>
              <TrophyOutlined /> 总积分
            </div>
            <div style={{ fontSize: '32px', fontWeight: 'bold', color: '#faad14' }}>
              {stats.total_points}
            </div>
          </div>
        </div>
      ) : (
        <div style={{ textAlign: 'center', padding: '40px 0' }}>
          <Text type="secondary">暂无统计数据</Text>
        </div>
      )}
    </Modal>
  );
};

export default TodayStatsModal;
